package org.zbclan.bf2.rcon.home.server;

import java.util.Hashtable;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbclan.bf2.rcon.common.server.ServerModel;
import org.zbclan.bf2.rcon.common.shared.GamePlayObject;
import org.zbclan.bf2.rcon.home.shared.GetGameModeListCommand;
import org.zbclan.bf2.rcon.home.shared.GetGameModeListResult;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class GetGameModeListHandler implements
		ActionHandler<GetGameModeListCommand, GetGameModeListResult> {

	private static final Logger logger = LoggerFactory
			.getLogger(GetGameModeListHandler.class);

	// private final Log logger;
	private final Provider<ServletContext> servletContext;
	private final Provider<HttpServletRequest> servletRequest;
	private ServerModel serverModel;

	@Inject
	public GetGameModeListHandler(
			final Provider<ServletContext> servletContext,
			final Provider<HttpServletRequest> servletRequest,
			ServerModel serverModel) {
		// this.logger = logger;
		this.servletContext = servletContext;
		this.servletRequest = servletRequest;
		this.serverModel = serverModel;
	}

	public GetGameModeListResult execute(final GetGameModeListCommand cmd,
			final ExecutionContext context) throws ActionException {

		try {
			String name = cmd.getName();

			Hashtable<String, GamePlayObject> gpoMap = serverModel.getLevels()
					.get(name);

			Set<String> gameModes = gpoMap.keySet();
			String[] modes = gameModes.toArray(new String[gameModes.size()]);
			// for (int i = 0; i < modes.length; i++) {
			// String longName = modes[i];
			// modes[i] = longName.substring(ServerZip.GPO_PREFIX.length(),
			// longName.length() - ServerZip.GPO_SUFFIX.length());
			// }

			GetGameModeListResult result = new GetGameModeListResult();
			// result.setSizes(new String[] { "16", "32", "64" });
			result.setModes(modes);
			return result;

		} catch (Exception cause) {
			logger.error("Unable to send message", cause);

			throw new ActionException(cause);
		}
	}

	public void rollback(final GetGameModeListCommand action,
			final GetGameModeListResult result, final ExecutionContext context)
			throws ActionException {
		// Nothing to do here
	}

	public Class<GetGameModeListCommand> getActionType() {
		return GetGameModeListCommand.class;
	}
}